package dao;

import util.DBHelper;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class CartDao {

    // 购物车 查询
    public List<Map<String, Object>> selectCard(String name, String uid){
        String sql = "select shoppingid,carid ,p.image, p.proid, proname, price, c.num from receshopping r inner join shopping_user u on r.uid = u.uid  INNER JOIN shopping_cart c ON u.uid=c.uid INNER JOIN shopping_product p ON c.proid=p.proid  where u.uid = ? GROUP BY carid";
        List<String> params = new ArrayList<>();
        params.add(uid);
        if ( name !=null && name.trim().isEmpty() ==false){
            sql += " and proname like ? ";
            params.add("%" + name + "%");
        }
        return DBHelper.selectListMap(sql, params.toArray());
    }

    // 购物车 购买(大订单)
    public int saveOrder(String uid, String paymenttype,String status, String paymenttime,String time, String totalprice,String shoppingid) throws SQLException {
        String sql = "insert into shopping_order values(default, ?, ?, ?, ?, null, null, ?, ?,?);";
        final Connection c = DBHelper.getConnection();
        final PreparedStatement ps = c.prepareStatement(sql, com.mysql.jdbc.Statement.RETURN_GENERATED_KEYS);

        ps.setObject(1, uid);
        ps.setObject(2, status);
        ps.setObject(3, paymenttype);
        ps.setObject(4, paymenttime);
        ps.setObject(5, time);
        ps.setObject(6, totalprice);
        ps.setObject(7, shoppingid);

        ps.executeUpdate();

        final ResultSet rs = ps.getGeneratedKeys();
        rs.next();
        return rs.getInt(1);
    }

    // 购物车 购买(小订单)
    public int saveOrderdetail(String orderid, String proid, String currentprice, String quantity){
        String sql = "insert into orderdetail values(default, ?, ?, ?, ?, null, null, 0, null)";
        return DBHelper.update(sql, orderid, proid, currentprice, quantity);
    }

    // 删除
    public int removeCard(String carid){
        String sql = "delete from shopping_cart where carid = ?";
        return DBHelper.update(sql, carid);
    }
    //添加购物车
    public int addData(String uid,String num,String proid){
        String sql ="insert into shopping_cart values(default,?,?,?)";
        return DBHelper.update(sql,uid,num,proid);
    }

    //查询购物车中是否存在该商品
    public Map<String, Object> queryDataByProid(String uid,String proid){
        String sql = "select * from shopping_cart where uid = ? and proid = ?";
        return DBHelper.selectOneMap(sql,uid,proid);
    }

    //商品数量加一
    public int updateNum(String uid,String proid){
        String sql ="update shopping_cart set num=num+1 where uid = ? and proid = ?  ";
        return DBHelper.update(sql,uid,proid);
    }
}